package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.config.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrdersDetailService ordersDetailService;

    /**
     * 提交订单
     *
     * @param orders
     * @param session
     * @return
     */
    @PostMapping("/submit")
    public R subOrder(@RequestBody Orders orders, HttpSession session) {
        //雪花算法生成id
        long orderId = IdWorker.getId();
        //获取订单的地址id
        Long addressBookId = orders.getAddressBookId();
        //获取到详细地址
        AddressBook address = addressBookService.getById(addressBookId);
        //获取当前用户信息
        User user = (User) session.getAttribute("user");
        Long userId = user.getId();
        //根据用户id获取购物车详细信息
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(lqw);
        //定义购物车内菜品总价
        BigDecimal totalPrice = new BigDecimal(0);
        //将购物车菜品信息复制到订单详情orderDetail
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart, orderDetail);
            //单独设置订单id
            orderDetail.setOrderId(orderId);
            //单独单个菜品设置总金额
            BigDecimal amount = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(amount.multiply(number));
            orderDetails.add(orderDetail);
            //购物车菜品总金额
            totalPrice = totalPrice.add(orderDetail.getAmount());
        }
        //将菜品详情存入orderDetail表
        ordersDetailService.saveBatch(orderDetails);
        //保存订单数据,一些属性需要单独设置
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1.待付款  2.待派送  3.已派送  4.已完成  5.已取消
        orders.setAmount(totalPrice); //订单总金额
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单编号
        orders.setUserName("CJJJ");//用户名
        orders.setConsignee(address.getConsignee());//收货人
        orders.setPhone(address.getPhone());//收货人联系电话
        //设置省市区详细地址
        String provinceName = address.getProvinceName() == null ? "" : address.getProvinceName();
        String cityName = address.getCityName() == null ? "" : address.getCityName();
        String districtName = address.getDistrictName() == null ? "" : address.getDistrictName();
        String detail = address.getDetail() == null ? "" : address.getDetail();

        orders.setAddress(provinceName + cityName + districtName + detail);

        ordersService.save(orders);
        //删除购物车数据
        //根据当前登录用户id删除购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw2 = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(lqw2);

        return R.success(null);
    }

    /**
     * 用户订单分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R pageQurry(Integer page, Integer pageSize) {

        IPage<Orders> pageInfo = new Page<>(page, pageSize);
        //获取userId
        Long userId = BaseContext.getCurrentId();
        //根据userId获取用户所有订单id
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, userId);
        //List<Orders> ordersList = ordersService.list(lqw);
        lqw.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageInfo, lqw);

        List<Orders> ordersList = pageInfo.getRecords();

        List<OrdersDto> ordersDtos = new ArrayList<>();
        //根据订单id获得ordersDetail
        for (Orders order : ordersList) {
            Long orderId = order.getId();
            LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> orderDetailList = ordersDetailService.list(lqw2);

            OrdersDto ordersDto = new OrdersDto();
            BeanUtil.copyProperties(order, ordersDto);
            ordersDto.setOrderDetails(orderDetailList);

            ordersDtos.add(ordersDto);
        }
        //ordersService.page(pageInfo,lqw);
        //List<Orders> records = pageInfo.getRecords();
        int total = (int) pageInfo.getTotal();

        Map map = new HashMap();

        map.put("records", ordersDtos);
        map.put("total", total);

        return R.success(map);
        //return R.error("已经到底了");
    }

    /**
     * 后台所有订单按条件分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R pageQurryOrder(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        log.info("开始时间是:{}", beginTime);
        log.info("结束时间是:{}", endTime);
        //分页构造器
        IPage<Orders> pageInfo = new Page<>(page, pageSize);
        //获取所有订单信息
        //条件构造器
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(number), Orders::getId, number);
        lqw.between(beginTime != null && endTime != null, Orders::getOrderTime, beginTime, endTime);
        lqw.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageInfo, lqw);

        List<Orders> ordersList = pageInfo.getRecords();
        int total = (int) pageInfo.getTotal();

        //创建一个map存放需要返回的响应数据
        Map map = new HashMap<>();

        map.put("records", ordersList);
        map.put("total", total);

        return R.success(map);
    }

    /**
     * 修改订单状态
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R updateAddrStatus(@RequestBody Orders orders) {
        //获取前端传回来的数据
        Long ordersId = orders.getId();
        Integer status = orders.getStatus();

        Orders order = ordersService.getById(ordersId);
        order.setStatus(status);

        ordersService.updateById(order);

        return R.success("修改成功");
    }

    /**
     * 再来一单
     *
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R orderAgain(@RequestBody Orders orders) {
        //获取前端传过来的订单id
        Long ordersId = orders.getId();
        Orders order = ordersService.getById(ordersId);
        //获取用户id
        Long userId = order.getUserId();
        //获取当前订单内的菜品详情
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId, ordersId);
        List<OrderDetail> orderDetailList = ordersDetailService.list(lqw);

        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        //将菜品放入购物车
        for (OrderDetail orderDetail : orderDetailList) {

            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtil.copyProperties(orderDetail, shoppingCart);
            //userId需要单独设置
            shoppingCart.setUserId(userId);

            shoppingCarts.add(shoppingCart);
        }
        shoppingCartService.saveBatch(shoppingCarts);

        return R.success(null);
    }
}
